package com.bw.lib_base.mvi

import android.content.Intent
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.lib_base.entity.Res
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel<Uiintent:IUiIntent>:ViewModel() {

    val channel = Channel<Uiintent>()

    //初始化状态
    private var state= MutableStateFlow<UiState>(UiState.onLoading)//存储 UI 状态

    val uiState:StateFlow<UiState>

        //uiState（StateFlow）将状态变化推送给 UI 层。
        get() = state.asStateFlow()//暴露为只读 StateFlow，供 UI 层观察

    init {

        viewModelScope.launch {
                //等待接受
            channel.receiveAsFlow().collect{//用于接收 UI 层发送的意图 如按钮点击、页面跳转请求）
                handlerIntent(it)//接收到意图
            }

        }



    }

    //处理意图
    abstract fun handlerIntent(it:Uiintent)

    //发送意图 上方init里接收到意图
    //intent:意图
    fun sendIntent(intent:Uiintent){

        viewModelScope.launch {

            channel.send(intent)

        }
    }

    //网络请求
     fun <T>httpRequest(request:Flow<Res<T>>){

         viewModelScope.launch {

             request.flowOn(Dispatchers.IO)
                 .catch {
                     Log.i("lr",it.message.toString())
                 }.collect {
                     if(it.code==200){
                         state.value=UiState.onSuccess(it.data)
                     }else{
                         state.value=UiState.Onerr(it.message)
                     }
                 }
         }

    }

}